/*
 * Copyright 2003-2006 The Apache Software Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.nanhill.commons.id.serial;

import org.nanhill.commons.id.AbstractLongIdentifierGenerator;

/**
 * <code>LongGenerator</code> is an Identifier Generator that generates an
 * incrementing number as a Long object.
 * 
 * <p>
 * If the <code>wrap</code> argument passed to the constructor is set to
 * <code>true</code>, the sequence will wrap, returning negative values when
 * {@link Long#MAX_VALUE} reached; otherwise an {@link IllegalStateException}
 * will be thrown.
 * </p>
 * 
 * @author Commons-Id team
 * @version $Id: LongGenerator.java,v 1.1 2006/09/20 06:56:00 alin Exp $
 */
public class LongGenerator extends AbstractLongIdentifierGenerator {

	/** Should the counter wrap. */
	private boolean wrapping;

	/** The counter. */
	private long count = 0;

	/**
	 * Constructor.
	 * 
	 * @param wrap
	 *            should the factory wrap when it reaches the maximum long value
	 *            (or throw an exception)
	 * @param initialValue
	 *            the initial long value to start at
	 */
	public LongGenerator(boolean wrap, long initialValue) {
		super();
		this.wrapping = wrap;
		this.count = initialValue;
	}

	/**
	 * Getter for property wrap.
	 * 
	 * @return <code>true</code> if this generator is set up to wrap.
	 * 
	 */
	public boolean isWrap() {
		return wrapping;
	}

	/**
	 * Sets the wrap property.
	 * 
	 * @param wrap
	 *            value for the wrap property
	 * 
	 */
	public void setWrap(boolean wrap) {
		this.wrapping = wrap;
	}

	public long nextLongIdentifier() {
		long value = 0;
		if (wrapping) {
			synchronized (this) {
				value = count++;
			}
		} else {
			synchronized (this) {
				if (count == Long.MAX_VALUE) {
					throw new IllegalStateException(
							"The maximum number of identifiers has been reached");
				}
				value = count++;
			}
		}
		return value;
	}
}
